package com.infocollect.project.api.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.infocollect.project.api.service.ITappUserService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

public class TokenService {
    TokenService(){
    }
    public  static  TokenService Ins=new TokenService();
    public String getToken(String userID,String password) {
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 60* 60 * 1000;//一小时有效时间
        Date end = new Date(currentTime);
        String token = "";

        token = JWT.create().withAudience(userID).withIssuedAt(start).withExpiresAt(end)
                .sign(Algorithm.HMAC256(password));
        return token;
    }
    public Boolean cheackToken(String token,String passWord){
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(passWord)).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new RuntimeException("401");
        }
        return true;

    }
    public String getCookies(HttpServletRequest request){
        //HttpServletRequest 装请求信息类
        //HttpServletRespionse 装相应信息的类
        //   Cookie cookie=new Cookie("sessionId","CookieTestInfo");
       String authorstr =  request.getHeader("Authorization");//.getCookies();
       if(StringUtils.isNotBlank(authorstr)){
           authorstr=authorstr.replace("Bearer ","");
       }else{
           Cookie[] cookies =  request.getCookies();
           if(cookies != null){
               for(Cookie cookie : cookies){
                   if(cookie.getName().equals("Authorization")){
                       return cookie.getValue();
                   }
               }
           }
       }
        return  authorstr;
    }

    public Boolean CheackLogin(HttpServletRequest request, ITappUserService tappUserService) throws IOException {
        String token =getCookies(request);// request.getHeader("token");// 从 http 请求头中取出 token
     //   System.out.println("进入preHandle,token:"+token);
        // 执行认证
        if (token == null||token.length()==0) {
            return false;
        }
        // 获取 token 中的 user id
        String currentuserJson;
        try {
            currentuserJson = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            return false;
        }
        if(currentuserJson!=null&&currentuserJson.length()>0){
//            try {
//                    NewUserInfoVO currentUserInfoVO = JSON.parseObject(currentuserJson,NewUserInfoVO.class);
//                    if(currentUserInfoVO ==null)
//                        return false;
//                    else{
//                            String userinfJson = WebApiHelper.AjaxGet("http://127.0.0.1:8980/js/a/sys/user/info?__ajax=json&__sid=" + currentUserInfoVO.getUsersessionid());
//                            if (userinfJson.contains("sessionid") && userinfJson.contains("result")) {
//                                return false;
//                            }
//                       return true;
//                    }
//            }catch (Exception ex){
//                return false;
//            }
            return true;
        }else {
           return false;
        }

    }
}
